"""
包括音频对象的相关信息
"""
import os
import wave

import pygame


class VideoInfo:
    pygame.mixer.init()

    def __init__(self, filePath: str):
        # 文件路径
        self.filePath = filePath
        # 所在目录
        self.dirPath = ''
        # 文件名，包括后缀
        self.filename = ''
        # 音频文件后缀
        self.filename_suffix = ''
        # 文件名排除文件名后缀
        self.filename_pre = ''

        # 文件长度, 单位秒
        self.length_sec = 0.0

        self.nchannels = ''
        self.sampwidth = ''
        self.framerate = ''
        self.nframes = ''
        self.comptype = ''
        self.compname = ''

        self.get_info()

    def get_info(self):
        video_suffix_list = ['.mp3', '.wav']
        if self.filePath != '' and os.path.exists(self.filePath) and os.path.isfile(self.filePath):
            # 分解处文件名称
            if '/' not in self.filePath:
                self.filename = self.filePath
                self.dirPath = ''
            else:
                self.filename = self.filePath[self.filePath.rindex('/') + 1:]
                # 末尾直接为/字符
                self.dirPath = self.filePath[: self.filePath.rindex('/')+1]
            # 分解文件名和后缀
            for i in range(len(video_suffix_list)):
                if self.filename.endswith(video_suffix_list[i]):
                    self.filename_suffix = video_suffix_list[i]
                    self.filename_pre = self.filename[:-len(self.filename_suffix)]

            """wave模块读取文件信息"""
            file = None
            try:
                # 打开音频文件
                file = wave.open(self.filePath, 'r')
                # 获取音频数据
                params = file.getparams()
                self.nchannels = params.nchannels
                self.sampwidth = params.sampwidth
                self.framerate = params.framerate
                self.nframes = params.nframes
                self.comptype = params.comptype
                self.compname = params.compname
            except Exception as e:
                print(e)
            finally:
                if file is not None:
                    file.close()
            """pygame读取音频长度"""
            a = pygame.mixer.Sound(self.filePath)
            self.length_sec = a.get_length()

    def toString(self):
        string = '文件名:%s\n文件路径:%s\n音频时长:%s' % (self.filename, self.filePath, str(self.length_sec))
        return string
